package cn.enilu.itnews.controller;

import cn.enilu.itnews.entity.User;
import cn.enilu.itnews.service.UserService;
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Controller
@RequestMapping("/")
public class FrontController  extends BaseController {

	@Inject
	private UserService userService;

	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register(HttpServletRequest request, Model model) {
		return "front/register";
	}
	@RequestMapping(value = "register",method = RequestMethod.POST)
	public String doRegister(HttpServletRequest request,
							 @Valid User user, BindingResult result, Model model,
							 RedirectAttributes redirectAttrs) {
		model.addAttribute("user", user);
		if (result.hasErrors()) {
			return "redirect:/register";
		}
		user.setCreatedAt(DateTime.now());
		userService.create(user);
		redirectAttrs.addFlashAttribute("message", "创建成功!");
		return "redirect:/login";
	}


	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(Model model) {

		return "front/login";
	}
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String doLogin(HttpServletRequest request,Model model) {
		String nameOrEmail = request.getParameter("name");
		String password = request.getParameter("password");
		User user = userService.find(nameOrEmail);


		String cryptedPassword = encodePassword(password, user.getSalt());
		if(cryptedPassword.equals(user.getCryptedPassword())){
			 getRequest().getSession().setAttribute("currentUser",user);
			return "redirect:/";
		}else {
			return "redirect:/front/login";
		}
	}
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index2(Model model) {
		return "front/index";
	}

	@RequestMapping(value = "/no_permission")
	public String noPermission() {
		return "no_permission";
	}
	private HashFunction sha1 = Hashing.sha1();

	private String encodePassword(String password, String salt) {
		return sha1.hashString(password + "#" + salt, Charsets.UTF_8).toString();
	}



}
